package com.zzxx.controller;

import com.zzxx.pojo.SysLog;
import com.zzxx.service.SyslogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class SyslogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SyslogService service;
    private Date visitTime;

    @Pointcut("execution(* com.zzxx.controller.*.*(..))")
    public void pc(){
    }

    @Before("pc()")
    public void before(){
        visitTime = new Date();
    }

    @After("pc()")
    public void after(JoinPoint jp){
        //获得用户名
//        HttpSession session = request.getSession();
//        SecurityContext spring_security_context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        SecurityContext context = SecurityContextHolder.getContext();
        User principal = (User) context.getAuthentication().getPrincipal();
        String username = principal.getUsername();
        //获得ip
        String ip = request.getRemoteAddr();
        //获得url
        String url = request.getRequestURI();
        //获得执行时间
        Long executionTime = new Date().getTime() - visitTime.getTime();
        //访问方法
        //获得正在执行的处理器类
        Class target = jp.getTarget().getClass();
        if(target != SyslogController.class){
            String className =target.getName();
            String methodName = jp.getSignature().getName();
            String method = "类名:" + className + ",方法名:" + methodName;
            SysLog sysLog = new SysLog();
            sysLog.setId(UUID.randomUUID().toString().replaceAll("-",""));
            sysLog.setExecutionTime(executionTime);
            sysLog.setUrl(url);
            sysLog.setUsername(username);
            sysLog.setVisitTime(visitTime);
            sysLog.setMethod(method);
            service.addSyslog(sysLog);
        }
    }

}
